package com.mytravel

import com.android.architecture.extension.empty
import com.android.architecture.extension.valid
import com.android.architecture.helper.CacheHelper
import com.android.architecture.helper.JsonHelper
import com.google.gson.Gson

/**
 * Created by SuQi on 2024/9/26.
 * Describe:
 */
object AppCache {

    private const val KEY_KEY_BEAN = "AppCache"
    private var bean = initBean()

    private fun initBean(): AppBean {
        try {
            val jsonString = CacheHelper.getString(KEY_KEY_BEAN)
            if (jsonString.valid) {
                return JsonHelper.toBean(jsonString)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return AppBean()
    }

    private fun saveBean(): Boolean {
        val jsonString = Gson().toJson(bean)
        return CacheHelper.saveString(KEY_KEY_BEAN, jsonString)
    }

    fun saveUrl(url: String): Boolean {
        bean.url = url
        return saveBean()
    }

    fun getUrl() = bean.url

    fun saveSn(sn: String): Boolean {
        bean.sn = sn
        return saveBean()
    }

    fun getSn(): String {
        var sn = bean.sn
        if (bean.sn.empty) {
            sn = System.currentTimeMillis().toString()
            saveSn(sn)
        }
        return sn
    }

    fun saveIntervalTime(intervalTime: Int): Boolean {
        bean.intervalTime = intervalTime
        return saveBean()
    }

    fun getIntervalTime() = bean.intervalTime

    fun saveUploadTimes(uploadTimes: Int): Boolean {
        bean.uploadTimes = uploadTimes
        return saveBean()
    }

    fun getUploadTimes() = bean.uploadTimes

}